package com.zhdl.modules.prefiresys.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.common.eventbus.event.PreFireEvent;
import com.zhdl.common.ytools.DateTimeHelper;
import com.zhdl.common.ytools.EnumHelper;
import com.zhdl.hardware.callback.CommonCallback;
import com.zhdl.modules.prefiresys.entity.*;
import com.zhdl.modules.prefiresys.service.*;
import com.zhdl.modules.prefiresys.web.service.CollectService;
import com.zhdl.modules.protocol_rtu.SerialPortManager;
import com.zhdl.network.prefiretcp.before.DetectorCommonData;
import com.zhdl.network.prefiretcp.before.MemDevice;
import com.zhdl.network.service.FireService;
import com.zhdl.network.service.dto.FireParameter;
import com.zhdl.network.service.dto.SysHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 定时采集探测器数据
 */
@Slf4j
@Component
public class CollectDetector {

    private static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    final CollectService collectService;
    final DefAreaHourRecService areaHourRecService;
    final DetectorAreaInfoService detectorAreaInfoService;
    final DefAreaAlarmRecService alarmRecService;
    final DetectorSwitchRecService detectorSwitchRecService;
    final DetectorAnalogRecService detectorAnalogRecService;
    final DetectorHistoryDataService detectorHistoryDataService;
    final FireService fireService;

    @Autowired
    public CollectDetector(CollectService collectService, DefAreaHourRecService areaHourRecService, DetectorAreaInfoService detectorAreaInfoService, DefAreaAlarmRecService alarmRecService, DetectorSwitchRecService detectorSwitchRecService, DetectorAnalogRecService detectorAnalogRecService, DetectorHistoryDataService detectorHistoryDataService, FireService fireService) {
        this.collectService = collectService;
        this.areaHourRecService = areaHourRecService;
        this.detectorAreaInfoService = detectorAreaInfoService;
        this.alarmRecService = alarmRecService;
        this.detectorSwitchRecService = detectorSwitchRecService;
        this.detectorAnalogRecService = detectorAnalogRecService;
        this.detectorHistoryDataService = detectorHistoryDataService;
        this.fireService = fireService;
    }

    @Async
    @Scheduled(fixedRate = 1000)
    public void scheduledTask() {
        //log.debug("开始采集,采集探测器数据 {}", collectService.memDeviceList.values().size());
        for (MemDevice device : collectService.memDeviceList.values()) {
            try {
                if (SysHelper.debug) {
//                    testUpdate(device);
                }

//                byte[] bytes = device.getPkg().GeneralParamMonitor();
//                String cmd = HexUtil.encodeHexStr(bytes);
//                boolean comX5 = SerialPortManager.getInstance().sendDate("COM5", HexUtil.decodeHex("55 06 01 03 01 66 18 0A 12 0F 2E 03 05 78"), new CommonCallback<String>() {


                byte[] bytes = device.getPkg().GeneralParamMonitor();
                if (device.getDetectorAddr() == 0x05){
                    boolean comX5 = SerialPortManager.getInstance().sendDate("COM5", bytes, s -> {
                        PreFireEvent preFireEvent = new PreFireEvent();
                        preFireEvent.setType("com");
                        preFireEvent.setPort("COM5");
                        AfterStrategyParam afterStrategyParam = new AfterStrategyParam();
                        afterStrategyParam.setExpectResults(s);
                        preFireEvent.setEvent(afterStrategyParam);
                        EventBusCenter.getEventBus().post(preFireEvent);
                    });
                } else if (device.getDetectorAddr() == 0x06){
                    boolean comX6 = SerialPortManager.getInstance().sendDate("COM6", bytes, s -> {
                        PreFireEvent preFireEvent = new PreFireEvent();
                        preFireEvent.setType("com");
                        preFireEvent.setPort("COM6");
                        AfterStrategyParam afterStrategyParam = new AfterStrategyParam();
                        afterStrategyParam.setExpectResults(s);
                        preFireEvent.setEvent(afterStrategyParam);
                        EventBusCenter.getEventBus().post(preFireEvent);
                    });
                };

                /* 获取设备详情参数 */
//                fireService.GeneralParamMonitor(device);
            } catch (Exception ex) {
                log.error("定时采集探测器数据出现异常, {}", ex.getMessage(), ex);
            }
        }
    }

    /**
     * 测试更新缓存数据，随机产生一些测试数据
     *
     * @param device d
     */
    public void testUpdate(MemDevice device) {
        LocalTime now = LocalTime.now();
        //collectService.sseResp.setElectricQuantity(now.getSecond());

        // test
        String areaId = device.getArea1Id();
        collectService.sseResp.getAreaList().get(areaId).setParticlePercent(now.getSecond());
        collectService.sseResp.getAreaList().get(areaId).setSmokePercent(now.getSecond());
        collectService.sseResp.getAreaList().get(areaId).setStatus((byte) RandomUtil.randomInt(0, 5));
        collectService.sseResp.getAreaList().get(areaId).setContRunTime(DateTimeHelper.secondToTimeString(RandomUtil.randomLong(0, 6000000)));
    }

    /**
     * 更新内存信息
     *
     * @param device
     * @param //allPara
     */
    @Async
    public void updateMemInfo(MemDevice device, FireParameter allPara) throws Exception {

        collectService.sseResp.getAreaList().get(device.getArea1Id()).setStatus(allPara.getAlarmStatus1());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setParticlePercent(allPara.getParticlePercent1());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setSmokePercent(allPara.getSmokePercent1());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setParticleModuleStatus(allPara.getParticleModuleStatus() == 0 ? "正常" : "异常");
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setSmokeModuleStatus(allPara.getSmokeModuleStatus() == 0 ? "正常" : "异常");
        List<String> checkUnitStatus = EnumHelper.getCheckUnitStatus(allPara.getCheckUnitStatus());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setCheckUnitStatus(checkUnitStatus);
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setMuteAlarmSound(allPara.isMuteAlarmSound());

        collectService.sseResp.getAreaList().get(device.getArea1Id()).setEnvHumidity(allPara.getEnvHumidity());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setEnvTemperature(allPara.getEnvTemperature());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setServiceVoltage(allPara.getServiceVoltage());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setDetectPressure(allPara.getDetectPressure());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setSamplingFlow1(allPara.getSamplingFlow1());
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setVacuumPressure(allPara.getVacuumPressure());

        // 连续运行时间就显示心跳累计值就可以
        collectService.sseResp.getAreaList().get(device.getArea1Id()).setContRunTime(DateTimeHelper.secondToTimeString(allPara.getHeartNum()));

        collectService.sseResp.getAreaList().get(device.getArea1Id()).setOnlineStatus(true);

        StringBuilder stringBuilderLog = new StringBuilder();
        stringBuilderLog.append(" heartNum: ").append(allPara.getHeartNum());
        stringBuilderLog.append(" detectorStatus: ").append(allPara.getDetectorStatus());
        stringBuilderLog.append(" checkUnitStatus: ").append(Arrays.toString(allPara.getCheckUnitStatus()));
        stringBuilderLog.append(" checkUnitStatusValue: ").append(allPara.getCheckUnitStatusValue());
        stringBuilderLog.append(" detectorModuleStatus: ").append(allPara.getDetectorModuleStatus());
        stringBuilderLog.append(" particleModuleStatus: ").append(allPara.getParticleModuleStatus());
        stringBuilderLog.append(" smokeModuleStatus: ").append(allPara.getSmokeModuleStatus());
        stringBuilderLog.append(" muteAlarmSound: ").append(allPara.isMuteAlarmSound());
        stringBuilderLog.append(" alarmStatus1: ").append(allPara.getAlarmStatus1());
        stringBuilderLog.append(" particleCount1: ").append(allPara.getParticleCount2());
        stringBuilderLog.append(" particlePercent1: ").append(allPara.getParticlePercent1());
        stringBuilderLog.append(" smokeCount1: ").append(allPara.getSmokeCount1());
        stringBuilderLog.append(" smokePercent1: ").append(allPara.getSmokePercent1());
        stringBuilderLog.append(" serviceVoltage: ").append(allPara.getServiceVoltage());
        stringBuilderLog.append(" flowSpeedSensorEnable1: ").append(allPara.isFlowSpeedSensorEnable1());
        stringBuilderLog.append(" samplingFlow1: ").append(allPara.getSamplingFlow1());
        stringBuilderLog.append(" samplingFlow2: ").append(allPara.getSamplingFlow2());
        stringBuilderLog.append(" samplingFlow3: ").append(allPara.getSamplingFlow3());
        stringBuilderLog.append(" samplingFlow4: ").append(allPara.getSamplingFlow4());

        log.debug(stringBuilderLog.toString());

    }

    String eventIdLast = "";

    Map<String, String> eventIdMaps = new ConcurrentHashMap<>();

    @Resource
    private EventRecordsService eventRecordsService;

    /**
     * 保存事件信息
     */
    public String addEventRecords(MemDevice device, FireParameter allPara) {
        boolean byEventStatus = eventRecordsService.findByEventStatus(false);
        /* 如果为true 则为空 添加一条 */
        if (byEventStatus) {
            EventRecords eventRecords = new EventRecords();
            eventRecords.setEventStatus(false);
            LocalDateTime localDateTime = LocalDateTime.now();
            String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            eventRecords.setStartTime(format);
            eventRecords.setDetectorId(device.getDeviceId());
            eventRecords.setAreaId(device.getArea1Id());
            EventRecords afterData = eventRecordsService.addEventRecords(eventRecords);
            return afterData.getId();
        } else {
            return "";
        }
    }

    public String updateEventRecords(String eventId) {
        boolean byEventStatus = eventRecordsService.findByEventStatus(false);
        if (!byEventStatus && eventId != null) {
            EventRecords eventRecords = eventRecordsService.findByEventId(eventId);
            if (eventRecords != null) {
                eventRecords.setEventStatus(true);
                LocalDateTime localDateTime = LocalDateTime.now();
                String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                eventRecords.setEndTime(format);
                EventRecords eventRecordsOk = eventRecordsService.updateEventRecords(eventRecords);
                return eventRecordsOk.getId();
            }
        }
        return "";
    }

    Map<Short, LastDataFire> dataFireMap = new ConcurrentHashMap<>();

    /**
     * 更新数据库信息
     *
     * @param device
     * @param //allPara
     */
    @Async
    public synchronized void updateDbInfo(MemDevice device, FireParameter allPara) {
        try {
            /* 保存当次 报警信息 报警状态 烟雾浓度 和 颗粒物浓度 */
            LastDataFire lastDataFire = new LastDataFire();
            lastDataFire.setDetWarnStatus(allPara.getAlarmStatus1());
            lastDataFire.setSmokePercent(allPara.getSmokePercent1());
            lastDataFire.setParticlePercent(allPara.getParticlePercent1());

            /* 保存防区小时浓度数据 每次都保存 */
            SaveAreaHourData(device, allPara);
            /* 保存开关量和模拟量 每次都保存 */
            saveSwitchAndAnalog(device, allPara);

            /* 根据探测器地址 获取上一次的报警数据 */
            LastDataFire lastDataFire1 = dataFireMap.get(device.getDetectorAddr());
            /* 判断报警信息是否与上次相同 如果是第一次，则直接保存，如果有相同的，则不进行处理 */
            if (lastDataFire1 != null) {
                /* 获取上次报警状态 */
                byte detWarnStatus = dataFireMap.get(device.getDetectorAddr()).getDetWarnStatus();
                /* 获取本次报警状态 */
                byte alarmStatus1 = allPara.getAlarmStatus1();

                /* 判断上一条报警记录是否为0，如果为0的话，则生成一条事件 */
                if (detWarnStatus == 0) {
                    // 判断报警状态是否为0
                    if (alarmStatus1 != 0) {
                        // 当前如果有报警的话，则新增一条报警记录 返回事件的Id
                        String eventId = addEventRecords(device, allPara);
                        if (!eventId.isEmpty()) {
                            eventIdMaps.put(device.getArea1Id(), eventId);
                        }
                        log.info("从0开始生成的报警事件记录Id为:{}", eventId);
                    }
                    /* 判断上一条报警记录是否为5，如果为5的话，则结束当前事件 */
                } else {
                    // 判断 当前报警状态如果为 0 则 结束事件
                    if (alarmStatus1 == 0) {
                        String eventId = updateEventRecords(eventIdMaps.get(device.getArea1Id()));
                        log.info("报警事件记录结束的Id为:{}" , eventId);
                    }
                }

                /* 判断是不是正常状态 */
                if (allPara.getAlarmStatus1() != 0) {
                    /* 获取上次报警状态 */
                    LastDataFire lastDataFireMap = dataFireMap.get(device.getDetectorAddr());
                    if (lastDataFire.getDetWarnStatus() != lastDataFireMap.getDetWarnStatus()) {
                        device.setEventId(eventIdMaps.get(device.getArea1Id()));
                        // 有报警时保存报警记录
                        SaveAlarmRec(device, allPara);
                    }
                } else {
                    // 有报警时保存报警记录
                    SaveAlarmRec(device, allPara);
                }

                /* 保存常规参数，如果与上次相同，则不保存，累计次数 */
                if (lastDataFire.getSmokePercent() != 0 || lastDataFire.getParticlePercent() != 0) {
                    /* 获取上次报警状态 */
                    LastDataFire lastDataFireMap = dataFireMap.get(device.getDetectorAddr());
                    if (lastDataFire.getSmokePercent() != lastDataFireMap.getSmokePercent() ||
                            lastDataFire.getParticlePercent() != lastDataFireMap.getParticlePercent()) {
                        // 保存常规参数，有变化保存
                        SaveHistoryData(device, allPara);
                    }
                }

            } else {
                //判断是否上电就为报警状态
                if (allPara.getAlarmStatus1() != 0){
                    // 当前如果有报警的话，则新增一条报警记录 返回事件的Id
                    String eventId = addEventRecords(device, allPara);
                    if (!eventId.isEmpty()) {
                        eventIdMaps.put(device.getArea1Id(), eventId);
                    }
                    log.info("从报警状态开始生成的报警事件记录Id为:{}", eventId);
                }

                // 保存报警信息，有变化保存
                SaveAlarmRec(device, allPara);
                // 保存常规参数，有变化保存
                SaveHistoryData(device, allPara);
            }

            //清除上次火前数据
//            for (Short i : dataFireMap.keySet()) {
//                dataFireMap.remove(i);
//            }
            dataFireMap.remove(device.getDetectorAddr());
            //保存本次火前数据
            dataFireMap.put(device.getDetectorAddr(), lastDataFire);
        } catch (Exception ex) {

        }
    }

    /**
     * 保存常规则参数数据
     *
     * @param device
     * @param //allPara
     */
    private void SaveAlarmRec(MemDevice device, FireParameter allPara) {

        /* 获取当前时间 */
        String curDateTime = DateUtil.now();

        //如果报警状态不为0，则保留
        if (allPara.getAlarmStatus1() != 0) {
            // 判断状态是否有变化
            if (allPara.getAlarmStatus1() != device.lastAlarmStatus) {

                DefAreaAlarmRec newRecords = alarmRecService.findNewRecords();
                if (newRecords != null && newRecords.getEndTime().equals("2000-01-01 00:00:00")) {
                    newRecords.setEndTime(curDateTime);
                    newRecords.setDurationSec(DateTimeHelper.calcDurationSec(newRecords.getStartTime(), newRecords.getEndTime()));
                    alarmRecService.update(newRecords, newRecords.getId());
                }

                //增加报警记录
                DefAreaAlarmRec alarmDto = new DefAreaAlarmRec();
                alarmDto.setId(IdUtil.fastSimpleUUID());
                alarmDto.setDetectorId(device.getDeviceId());
                alarmDto.setAreaId(device.getArea1Id());
                alarmDto.setAlarmStatus(device.lastAlarmStatus);//上一个报警状态
                alarmDto.setNextAlarmStatus(allPara.getAlarmStatus1());//当前报警状态
                // 保存创建时间为当前时间
                alarmDto.setStartTime(curDateTime);
                // 结束时间暂时空着
                alarmDto.setEndTime("2000-01-01 00:00:00");
                //相差时间 为 0
                alarmDto.setDurationSec(0L);

                alarmDto.setReportStatus(0);//6-14 上报标志初始为0
                alarmDto.setParticlePercent(allPara.getParticlePercent1());//6-19 数据分析统计需要
                alarmDto.setSmokePercent(allPara.getSmokePercent1());//6-19 数据分析统计需要
                alarmDto.setProjectId(collectService.factoryLocalHost.projectId);
                alarmDto.setEventId(device.getEventId());
                alarmRecService.insert(alarmDto);

                device.lastAlarmStatus = allPara.getAlarmStatus1();
            }
        } else {
            if (device.getLastAlarmStatus() != 0) {
                DefAreaAlarmRec newRecords = alarmRecService.findNewRecords();
                if (newRecords != null && newRecords.getEndTime().equals("2000-01-01 00:00:00")) {
                    newRecords.setEndTime(curDateTime);
                    newRecords.setDurationSec(DateTimeHelper.calcDurationSec(newRecords.getStartTime(), newRecords.getEndTime()));
                    alarmRecService.update(newRecords, newRecords.getId());
                }
                device.lastAlarmStatus = allPara.getAlarmStatus1();
                device.setLastAlarmAt(curDateTime);
            }
        }
    }

    /**
     * 保存常规则参数数据
     *
     * @param device
     * @param //allPara
     */
    private void SaveHistoryData(MemDevice device, FireParameter allPara) {
        //当前时间
        String curDateTime = DateUtil.now();
        //查询最新的一条记录
        DetectorHistoryData newRecords = detectorHistoryDataService.findNewRecords();

        //判断是否查询出来
        if (newRecords != null && newRecords.getEndTime().equals("2000-01-01 00:00:00")) {
            newRecords.setEndTime(curDateTime);
            detectorHistoryDataService.update(newRecords, newRecords.getId());
        }

        //保存历史记录
        DetectorHistoryData detectorHistoryData = new DetectorHistoryData();
        detectorHistoryData.setDetectorStatus(allPara.getDetectorStatus());
        detectorHistoryData.setDetectorUnitStateValue(allPara.getCheckUnitStatusValue());
        List<String> checkUnitStatus = EnumHelper.getCheckUnitStatus(allPara.getCheckUnitStatus());
        detectorHistoryData.setDetectorUnitState(String.join(",", checkUnitStatus));
        detectorHistoryData.setAlarmState(allPara.getAlarmStatus1());
        detectorHistoryData.setDetectorModuleStatus(allPara.getDetectorModuleStatus());
        detectorHistoryData.setParticleCount(allPara.getParticleCount1());
        detectorHistoryData.setParticlePercent(allPara.getParticlePercent1());
        detectorHistoryData.setSmokeCount(allPara.getSmokeCount1());
        detectorHistoryData.setSmokePercent(allPara.getSmokePercent1());

        // 这里实际上保存的是上次的记录，一个状态只有变成另一个状态时，才认为是结束，才会保存
        detectorHistoryData.setId(IdUtil.fastSimpleUUID());
        detectorHistoryData.setDetectorId(device.getDeviceId());
        detectorHistoryData.setAreaId(device.getArea1Id());
        detectorHistoryData.setStartTime(curDateTime);
        detectorHistoryData.setEndTime("2000-01-01 00:00:00");
        detectorHistoryData.setReportStatus(0);//6-16 上报标志初始为0
        detectorHistoryDataService.insert(detectorHistoryData);
    }

    /**
     * 保存开关量和模拟量
     *
     * @param device  内存信息
     * @param allPara 参数信息
     */
    public void saveSwitchAndAnalog(MemDevice device, FireParameter allPara) {
        // 保存开关量，每次都保存
        DetectorSwitchRec detectorSwitchRec = new DetectorSwitchRec();
        detectorSwitchRec.setId(IdUtil.fastSimpleUUID());
        detectorSwitchRec.setDetectorId(device.getDeviceId());
        detectorSwitchRec.setDi1(allPara.getDiStatus()[0]);
        detectorSwitchRec.setDi2(allPara.getDiStatus()[1]);
        detectorSwitchRec.setDi3(allPara.getDiStatus()[2]);
        detectorSwitchRec.setDi4(allPara.getDiStatus()[3]);
        detectorSwitchRec.setDo1(allPara.getDoStatus()[1]);
        detectorSwitchRec.setDo2(allPara.getDoStatus()[2]);
        detectorSwitchRec.setDo3(allPara.getDoStatus()[3]);
        detectorSwitchRec.setDo4(allPara.getDoStatus()[4]);
        detectorSwitchRecService.insert(detectorSwitchRec);

        // 保存模拟量，每次都保存
        DetectorAnalogRec detectorAnalogRec = new DetectorAnalogRec();
        detectorAnalogRec.setId(IdUtil.fastSimpleUUID());
        detectorAnalogRec.setDetectorId(device.getDeviceId());
        detectorAnalogRec.setAreaId(device.getArea1Id());
        detectorAnalogRec.setParticleCount(allPara.getParticleCount1());
        detectorAnalogRec.setParticlePercent(allPara.getParticlePercent1());
        detectorAnalogRec.setSmokeCount(allPara.getSmokeCount1());
        detectorAnalogRec.setSmokePercent(allPara.getSmokePercent1());
        detectorAnalogRec.setServiceVoltage(allPara.getServiceVoltage());
        detectorAnalogRec.setSamplingFlow1(allPara.getSamplingFlow1());
        detectorAnalogRec.setSamplingFlow2(allPara.getSamplingFlow2());
        detectorAnalogRec.setSamplingFlow3(allPara.getSamplingFlow3());
        detectorAnalogRec.setSamplingFlow4(allPara.getSamplingFlow4());
        detectorAnalogRec.setEnvTemperature(allPara.getEnvTemperature());
        detectorAnalogRec.setEnvHumidity(allPara.getEnvHumidity());
        detectorAnalogRec.setVacuumPressure(allPara.getVacuumPressure());
        detectorAnalogRec.setDetectPressure(allPara.getDetectPressure());
        detectorAnalogRecService.insert(detectorAnalogRec);
    }

    /**
     * 保存防区小时浓度数据
     *
     * @param device
     * @param //allPara
     */
    private void SaveAreaHourData(MemDevice device, FireParameter allPara) {

        // 增加当前小时防区浓度数据
        long opRes = areaHourRecService.addData(device.getDeviceId(), device.getArea1Id(), allPara.getParticlePercent1(), allPara.getSmokePercent1());
        if (opRes <= 0) log.error("保存防区小时浓度数据失败:{}", opRes);

    }

    //6-15
//    private void SaveAlarmRec(MemDevice device, FireParameter allPara) {
//
//        /* 判断当前报警状态是否为0 如果为0 则不保存 */
//        if (allPara.getAlarmStatus1() == 0) {
//            return;
//        }
//
//        // 判断状态是否有变化
//        if (allPara.getAlarmStatus1() != device.lastAlarmStatus) {
//            /* 获取当前事件 */
//            String curDateTime = DateUtil.now();
//
//            //增加报警记录
//            DefAreaAlarmRec alarmDto = new DefAreaAlarmRec();
//            alarmDto.setId(IdUtil.fastSimpleUUID());
//            alarmDto.setDetectorId(device.getDeviceId());
//            alarmDto.setAreaId(device.getArea1Id());
//            alarmDto.setAlarmStatus(device.lastAlarmStatus);//上一个报警状态
//            alarmDto.setNextAlarmStatus(allPara.getAlarmStatus1());//当前报警状态
//            alarmDto.setStartTime(device.lastAlarmAt);
//            alarmDto.setEndTime(curDateTime);
//            alarmDto.setDurationSec(DateTimeHelper.calcDurationSec(device.lastAlarmAt, curDateTime));
//            alarmDto.setReportStatus(0);//6-14 上报标志初始为0
//            alarmDto.setParticlePercent(allPara.getParticlePercent1());//6-19 数据分析统计需要
//            alarmDto.setSmokePercent(allPara.getSmokePercent1());//6-19 数据分析统计需要
//            alarmDto.setProjectId(collectService.factoryLocalHost.projectId);
//            alarmDto.setEventId(device.getEventId());
//            alarmRecService.insert(alarmDto);
//
//            // 状态有改变时保存数据库
//            //if (allPara.getAlarmStatus1() == 0) {
//            // 如果当前状态为正常
//            //     device.lastAlarmStatus = -1;
//            //} else {
//            // 当前状态仍然是异常，则缓存记录下来，直到下一次状态变化时，再保存数据库
//            device.lastAlarmStatus = allPara.getAlarmStatus1();
//            device.lastAlarmAt = curDateTime;
//            //}
//
//            //实时上报数据
//            String jsonString = JSON.toJSONString(alarmDto);
//            //String urlPath=new String("/api/alarmRec/addAlarmRec");
//            String urlPath = new String("/api/alarmRecSend/sendAlarmRec");
//            String returnResult = HttpClientUtil.reportDataByHttp(jsonString, urlPath);
//            //如果上报成功,更改上报标志为1
//            if (Integer.parseInt(returnResult) == HttpStatus.CREATED.value()) {
//                alarmDto.setReportStatus(1);
//                alarmRecService.updateIgnoreNull(alarmDto, alarmDto.getId());
//            }
//
//        }
//    }


//    private void SaveHistoryData(MemDevice device, FireParameter allPara) {
//
//        // 保存常规参数，有变化保存
//        String curDateTime = DateUtil.now();
//
//        if (device.lastData == null) {
//            // 如果上次没有，说明是刚启动，则当前数据直充为上次
//            device.lastData = new DetectorCommonData();
//            device.lastData.setStartTime(curDateTime);
//            List<String> checkUnitStatus = EnumHelper.getCheckUnitStatus(allPara.getCheckUnitStatus());
//            device.lastData.setDetectorUnitState(String.join(",", checkUnitStatus));
//            device.lastData.setAlarmState(allPara.getAlarmStatus1());
//            device.lastData.setDetectorModuleStatus(allPara.getDetectorModuleStatus());
//            device.lastData.setParticleCount(allPara.getParticleCount1());
//            device.lastData.setParticlePercent(allPara.getParticlePercent1());
//            device.lastData.setSmokeCount(allPara.getSmokeCount1());
//            device.lastData.setSmokePercent(allPara.getSmokePercent1());
//            return;
//        }
//
//        DetectorHistoryData detectorHistoryData = new DetectorHistoryData();
//        detectorHistoryData.setDetectorStatus(allPara.getDetectorStatus());
//        detectorHistoryData.setDetectorUnitStateValue(allPara.getCheckUnitStatusValue());
//        List<String> checkUnitStatus = EnumHelper.getCheckUnitStatus(allPara.getCheckUnitStatus());
//        detectorHistoryData.setDetectorUnitState(String.join(",", checkUnitStatus));
//        detectorHistoryData.setAlarmState(allPara.getAlarmStatus1());
//        detectorHistoryData.setDetectorModuleStatus(allPara.getDetectorModuleStatus());
//        detectorHistoryData.setParticleCount(allPara.getParticleCount1());
//        detectorHistoryData.setParticlePercent(allPara.getParticlePercent1());
//        detectorHistoryData.setSmokeCount(allPara.getSmokeCount1());
//        detectorHistoryData.setSmokePercent(allPara.getSmokePercent1());
//
//        // 这里实际上保存的是上次的记录，一个状态只有变成另一个状态时，才认为是结束，才会保存
//        detectorHistoryData.setId(IdUtil.fastSimpleUUID());
//        detectorHistoryData.setDetectorId(device.getDeviceId());
//        detectorHistoryData.setAreaId(device.getArea1Id());
//        detectorHistoryData.setStartTime(device.lastData.getStartTime());
//        detectorHistoryData.setEndTime(curDateTime);
//        detectorHistoryData.setReportStatus(0);//6-16 上报标志初始为0
//        detectorHistoryDataService.insert(detectorHistoryData);
//
//        // 保存后将本次数据更新为上次数据
//        device.lastData.setStartTime(curDateTime);
//        device.lastData.setDetectorUnitState(String.join(",", checkUnitStatus));
//        device.lastData.setAlarmState(allPara.getAlarmStatus1());
//        device.lastData.setDetectorModuleStatus(allPara.getDetectorModuleStatus());
//        device.lastData.setParticleCount(allPara.getParticleCount1());
//        device.lastData.setParticlePercent(allPara.getParticlePercent1());
//        device.lastData.setSmokeCount(allPara.getSmokeCount1());
//        device.lastData.setSmokePercent(allPara.getSmokePercent1());
//    }


}
